﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private Socket ServerSocket;
        private Socket CurrentClient;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Création de la socket

            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {

                IPHostEntry ipHostEntry = Dns.Resolve(Dns.GetHostName());

                IPAddress ipAddress = ipHostEntry.AddressList[0];

                richTextBoxStatus.AppendText("IP=" + ipAddress.ToString() + "\n");

                CurrentClient = null;

                ServerSocket.Bind(new IPEndPoint(ipAddress, 8000));


                //On la positionne en mode "écoute"

                ServerSocket.Listen(10);

                //Démarrage du thread avant la première connexion client

                Thread getReadClients = new Thread(new ThreadStart(getRead));

                getReadClients.Start();

                richTextBoxStatus.AppendText("Serveur à l'écoute\n");


                Thread waitConnection = new Thread(new ThreadStart(waitForClientConnection));

                waitConnection.Start();
               
            }


            catch (SocketException E)
            {

                richTextBoxStatus.AppendText(E.Message + "\n");

            }

        }

        private void waitForClientConnection()
        {

            while (true)
            {

                Console.WriteLine("Attente d'une nouvelle connexion...");

                //L'exécution du thread courant est bloquée jusqu'à ce qu'un

                //nouveau client se connecte

                CurrentClient = ServerSocket.Accept();

                Console.WriteLine("Nouveau client:" + CurrentClient.GetHashCode());

                Console.WriteLine("Nouveau client:" + CurrentClient);
                CurrentClient.Send(StrToByteArray("Bonjour client numero " + CurrentClient.GetHashCode()));



                //Stockage de la ressource dans l'arraylist acceptlist

                //acceptList.Add(CurrentClient);

            }
        }

        public static byte[] StrToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }

        private void getRead()
        {

            while (true)
            {

                if (CurrentClient != null && CurrentClient.Connected)
                {


                    byte[] msg = new byte[CurrentClient.Available];

                    CurrentClient.Receive(msg, msg.Length, SocketFlags.None);

                    String msgString = System.Text.Encoding.UTF8.GetString(msg);

                    Console.WriteLine(msgString);


                    CurrentClient.Send(StrToByteArray(msgString));

                }
            }

            //Thread.Sleep(10);

        }

    }

	
    
}
